// main-vue.js
// Vue 3 + Vue Router 单页 | 数据全走 localStorage | 购物车持久化已打通

const { createApp, reactive, computed, watch } = Vue;
const { createRouter, createWebHashHistory } = VueRouter;

/* ========== 工具：localStorage ========== */
const load = (k, def) => {
  try { return JSON.parse(localStorage.getItem(k)) ?? def; }
  catch { return def; }
};
const save = (k, v) => localStorage.setItem(k, JSON.stringify(v));

/* ========== 初始数据 ========== */
if (!localStorage.getItem("products")) save("products", [
  { id: 1, title: "二手教材《计算机基础》", price: 35, img: "img/book1.jpg", desc: "九成新", seller: "alice" },
  { id: 2, title: "二手无线鼠标", price: 45, img: "img/mouse.jpg", desc: "正常使用", seller: "bob" },
  { id: 3, title: "二手台灯", price: 20, img: "img/lamp.jpg", desc: "LED可调", seller: "carol" },
  { id: 4, title: "二手书包", price: 80, img: "img/backpack.jpg", desc: "9成新", seller: "dave" }
]);
if (!localStorage.getItem("users")) save("users", [
  { username: "alice", password: "123456" },
  { username: "bob", password: "123456" }
]);

/* ========== 全局响应式 store ========== */
const store = reactive({
  currentUser: load("currentUser", null),
  products: load("products", []),
  cart: load("cart", []),
  orders: load("orders", [])
});
watch(() => store.products, v => save("products", v), { deep: true });
watch(() => store.cart, v => save("cart", v), { deep: true });
watch(() => store.orders, v => save("orders", v), { deep: true });
watch(() => store.currentUser, v => save("currentUser", v));

/* ========== 公共方法 ========== */
const findProduct = id => store.products.find(p => p.id === id);

// ✅ 加入购物车（持久化）
function addToCart(productId) {
  if (!store.currentUser) { alert("请先登录"); return; }
  const p = findProduct(productId);
  if (!p) return;
  const exist = store.cart.find(i => i.id === productId);
  if (exist) exist.quantity++;
  else store.cart.push({ id: p.id, title: p.title, price: p.price, quantity: 1, seller: p.seller });
  alert("已加入购物车");
}

// ✅ 购物车数量修改 & 删除
function changeCartQuantity(index, delta) {
  const item = store.cart[index];
  if (!item) return;
  item.quantity += delta;
  if (item.quantity <= 0) store.cart.splice(index, 1);
}
function removeCartIndex(index) { store.cart.splice(index, 1); }

// ✅ 结算生成订单
function checkout() {
  if (!store.currentUser) { alert("请先登录"); return; }
  if (store.cart.length === 0) { alert("购物车为空"); return; }
  const total = store.cart.reduce((s, it) => s + it.price * it.quantity, 0);
  store.orders.push({
    id: Date.now(), user: store.currentUser.username,
    items: JSON.parse(JSON.stringify(store.cart)), total, status: "待发货"
  });
  store.cart = []; // 清空
  alert("下单成功");
  router.push("/orders");
}

/* ========== 组件：Navbar ========== */
const Navbar = {
  template: `
    <header>
      <h1 @click="$router.push('/')" style="cursor:pointer;">校易淘二手交易平台</h1>
      <nav>
        <router-link to="/">首页</router-link>
        <router-link to="/cart">购物车 (<span>{{ cartCount }}</span>)</router-link>
        <router-link to="/publish">发布商品</router-link>
        <router-link to="/myitems">我的商品</router-link>
        <router-link to="/orders">我的订单</router-link>
        <span v-if="!currentUser">
          <router-link to="/login">登录</router-link>
          <router-link to="/register">注册</router-link>
        </span>
        <span v-else>
          <strong>{{ currentUser.username }}</strong>
          <button class="small" @click="logout">退出</button>
        </span>
      </nav>
    </header>
  `,
  setup() {
    const currentUser = computed(() => store.currentUser);
    const cartCount = computed(() => store.cart.reduce((s, it) => s + it.quantity, 0));
    function logout() { store.currentUser = null; router.push("/"); }
    return { currentUser, cartCount, logout };
  }
};

/* ========== 组件：Home（商品列表 + 搜索） ========== */
const Home = {
  template: `
    <div class="container">
      <div class="search-area">
        <input v-model="keyword" placeholder="搜索商品或卖家..." @keyup.enter="search">
        <button @click="search">搜索</button>
        <button @click="reset">重置</button>
      </div>
      <div class="product-list">
        <div class="product-card" v-for="p in filtered" :key="p.id">
          <img :src="p.img" :alt="p.title" />
          <h3>{{ p.title }}</h3>
          <p class="price">￥{{ p.price }}</p>
          <p class="desc">{{ p.desc }}</p>
          <p class="seller">卖家：{{ p.seller }}</p>
          <button @click="addCart(p.id)">加入购物车</button>
        </div>
      </div>
    </div>
  `,
  setup() {
    const keyword = Vue.ref("");
    const filtered = computed(() => {
      const k = keyword.value.trim().toLowerCase();
      if (!k) return store.products;
      return store.products.filter(p =>
        p.title.toLowerCase().includes(k) || (p.seller && p.seller.toLowerCase().includes(k))
      );
    });
    function search() { /* filtered 自动更新 */ }
    function reset() { keyword.value = ""; }
    function addCart(id) { addToCart(id); }
    return { keyword, filtered, search, reset, addCart };
  }
};

/* ========== 组件：Cart（购物车管理） ========== */
const Cart = {
  template: `
    <div class="container">
      <h2 style="text-align:center">购物车</h2>
      <table v-if="cart.length">
        <thead><tr><th>商品</th><th>价格</th><th>数量</th><th>小计</th><th>操作</th></tr></thead>
        <tbody>
          <tr v-for="(it, idx) in cart" :key="it.id">
            <td>{{ it.title }}</td>
            <td>￥{{ it.price }}</td>
            <td>
              <button @click="dec(idx)">-</button>
              {{ it.quantity }}
              <button @click="inc(idx)">+</button>
            </td>
            <td>￥{{ (it.price * it.quantity) }}</td>
            <td><button @click="remove(idx)">删除</button></td>
          </tr>
        </tbody>
      </table>
      <p v-else>购物车空空如也，去首页逛逛吧！</p>
      <div style="text-align:right; margin-top:12px;">
        <strong>总价：{{ total }} 元</strong>
        <button @click="checkout" style="margin-left:12px;">结算</button>
      </div>
    </div>
  `,
  setup() {
    const cart = computed(() => store.cart);
    const total = computed(() => store.cart.reduce((s, it) => s + it.price * it.quantity, 0));
    function inc(i)  { changeCartQuantity(i, 1); }
    function dec(i)  { changeCartQuantity(i, -1); }
    function remove(i) { removeCartIndex(i); }
    return { cart, total, inc, dec, remove, checkout };
  }
};

/* ========== 其他组件（简略写法，保持结构一致） ========== */
const Publish = {
  template: `
    <div class="container">
      <h2 style="text-align:center">发布新商品</h2>
      <form @submit.prevent="submit">
        <input v-model="title"   placeholder="商品名称" required />
        <input v-model.number="price" type="number" min="0" placeholder="价格" required />
        <input v-model="img"     placeholder="图片链接" required />
        <textarea v-model="desc" placeholder="描述" rows="3"></textarea>
        <button type="submit">发布</button>
      </form>
    </div>
  `,
  setup() {
    const title = Vue.ref(""), price = Vue.ref(0), img = Vue.ref("img/default.jpg"), desc = Vue.ref("");
    function submit() {
      if (!store.currentUser) { alert("请先登录"); router.push("/login"); return; }
      store.products.push({ id: Date.now(), title: title.value, price: price.value, img: img.value, desc: desc.value, seller: store.currentUser.username });
      alert("发布成功"); router.push("/myitems");
    }
    return { title, price, img, desc, submit };
  }
};

const MyItems = {
  template: `
    <div class="container">
      <h2 style="text-align:center">我的商品</h2>
      <div v-if="!currentUser">请先登录查看你的发布</div>
      <div v-else>
        <div class="product-list" v-if="myList.length">
          <div class="product-card" v-for="p in myList" :key="p.id">
            <img :src="p.img" /><h3>{{ p.title }}</h3><p class="price">￥{{ p.price }}</p>
            <button @click="remove(p.id)">下架</button>
          </div>
        </div>
        <p v-else>你还没有发布任何商品</p>
      </div>
    </div>
  `,
  setup() {
    const currentUser = computed(() => store.currentUser);
    const myList = computed(() => store.products.filter(p => p.seller === store.currentUser?.username));
    function remove(id) { if (confirm("确定下架？")) store.products = store.products.filter(p => p.id !== id); }
    return { currentUser, myList, remove };
  }
};

const Orders = {
  template: `
    <div class="container">
      <h2 style="text-align:center">我的订单</h2>
      <div v-if="!currentUser">请先登录查看订单</div>
      <div v-else>
        <table v-if="myOrders.length">
          <thead><tr><th>订单号</th><th>商品</th><th>数量</th><th>总价</th><th>状态</th></tr></thead>
          <tbody>
            <tr v-for="o in myOrders" :key="o.id">
              <td>{{ o.id }}</td>
              <td><ul><li v-for="it in o.items">{{ it.title }} x {{ it.quantity }}</li></ul></td>
              <td>{{ o.items.reduce((s,it)=>s+it.quantity,0) }}</td>
              <td>{{ o.total }} 元</td>
              <td>{{ o.status }}</td>
            </tr>
          </tbody>
        </table>
        <p v-else>暂无订单记录</p>
      </div>
    </div>
  `,
  setup() {
    const currentUser = computed(() => store.currentUser);
    const myOrders = computed(() => store.orders.filter(o => o.user === store.currentUser?.username));
    return { currentUser, myOrders };
  }
};

const Login = {
  template: `
    <div class="container">
      <h2 style="text-align:center">用户登录</h2>
      <form @submit.prevent="submit">
        <input v-model="username" placeholder="用户名" required />
        <input v-model="password" type="password" placeholder="密码" required />
        <button type="submit">登录</button>
      </form>
    </div>
  `,
  setup() {
    const username = Vue.ref(""), password = Vue.ref("");
    function submit() {
      const users = load("users", []);
      const u = users.find(x => x.username === username.value && x.password === password.value);
      if (u) { store.currentUser = { username: u.username }; alert("登录成功"); router.push("/"); }
      else alert("用户名或密码错误");
    }
    return { username, password, submit };
  }
};

const Register = {
  template: `
    <div class="container">
      <h2 style="text-align:center">用户注册</h2>
      <form @submit.prevent="submit">
        <input v-model="username" placeholder="用户名" required />
        <input v-model="password" type="password" placeholder="密码" required />
        <button type="submit">注册</button>
      </form>
    </div>
  `,
  setup() {
    const username = Vue.ref(""), password = Vue.ref("");
    function submit() {
      const users = load("users", []);
      if (users.find(u => u.username === username.value)) { alert("用户名已存在"); return; }
      users.push({ username: username.value, password: password.value });
      save("users", users);
      alert("注册成功，请登录"); router.push("/login");
    }
    return { username, password, submit };
  }
};

/* ========== 路由 & 应用 ========== */
const routes = [
  { path: "/", component: Home },
  { path: "/cart", component: Cart },
  { path: "/publish", component: Publish },
  { path: "/myitems", component: MyItems },
  { path: "/orders", component: Orders },
  { path: "/login", component: Login },
  { path: "/register", component: Register }
];
const router = createRouter({ history: createWebHashHistory(), routes });
const App = { template: `<div><Navbar /><router-view /></div>`, components: { Navbar } };

createApp(App).use(router).mount("#app");